package com.smartcat.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.smartcat.bean.LoginUserBean;
import com.smartcat.bean.UserFunctionsBean;
import com.smartcat.dao.FunctionConfigMapper;
import com.smartcat.dao.UserFunctionMapMapper;
import com.smartcat.dao.UserInfoMapper;
import com.smartcat.model.FunctionConfig;
import com.smartcat.model.FunctionConfigExample;
import com.smartcat.model.UserFunctionMap;
import com.smartcat.model.UserFunctionMapExample;
import com.smartcat.service.LoadDataService;


@Service("loadDataService")
public class LoadDataServiceImpl implements LoadDataService{

	private FunctionConfigMapper functionConfigMapper;
	private UserInfoMapper userInfoMapper;
	private UserFunctionMapMapper userFunctionMapMapper;
	@Autowired
	public void setFunctionConfigMapper(FunctionConfigMapper functionConfigMapper) {
		this.functionConfigMapper = functionConfigMapper;
	}
	@Autowired
	public void setUserInfoMapper(UserInfoMapper userInfoMapper) {
		this.userInfoMapper = userInfoMapper;
	}
	@Autowired
	public void setUserFunctionMapMapper(UserFunctionMapMapper userFunctionMapMapper) {
		this.userFunctionMapMapper = userFunctionMapMapper;
	}




	@Override
	public List<FunctionConfig> loadFunctions() {
		FunctionConfigExample fcExample=new FunctionConfigExample();
		fcExample.or().andStatusEqualTo(0);
		return functionConfigMapper.selectByExample(fcExample);
	}

	@Override
	public UserFunctionsBean loadUserFunctions(int userId) {
		UserFunctionsBean ufBean=new UserFunctionsBean();
		ufBean.setUserInfo(userInfoMapper.selectByPrimaryKey(userId));
		UserFunctionMapExample ufExample=new UserFunctionMapExample();
		ufExample.or().andUserIdEqualTo(userId);
		List<UserFunctionMap> ufMap= userFunctionMapMapper.selectByExample(ufExample);
		List<Integer> functionIds=new ArrayList<Integer>();
		if(ufMap!=null && ufMap.size()>0){
		for(UserFunctionMap userFunction:ufMap){
			functionIds.add(userFunction.getFunctionId());
		}
		FunctionConfigExample example=new FunctionConfigExample();
		example.or().andFunctionIdIn(functionIds);
		ufBean.setFunctions(functionConfigMapper.selectByExample(example));
		}
		
		
		return ufBean;
	}
	@Override
	public Map<Integer, FunctionConfig> loadUserFunction(LoginUserBean user) {
		Map<Integer,FunctionConfig> userFunctions=new HashMap<Integer,FunctionConfig>();
		if(user==null){
			return userFunctions;
		}
		UserFunctionsBean userFunctionsBean=loadUserFunctions(user.getUserId());
		if(userFunctionsBean!=null){
		List<FunctionConfig> funcs=userFunctionsBean.getFunctions();
		 if(funcs!=null && funcs.size()>0){
			 for(FunctionConfig fconfig:funcs){
				 userFunctions.put(fconfig.getFunctionId(), fconfig);
			 }
		 }
		}
		return userFunctions;
		}

	
}
